<?php
/**
 * Description: 自取任务
 * User: devforma
 * Date: 15/1/7
 * Time: 12:07
 */

require __DIR__ . '/includes/utils.php';
class GetExtraTask implements iController {

    /**
     * api请求处理主函数
     * @param array $queryArgs 就是$_REQUEST变量
     * @return array api返回结果，必须含response_code
     */
    public function output($queryArgs) {
        global $uddb;

        if (validateUser($queryArgs) !== 1)
            return genOutput(1000);

        //获取当天已经取好的任务
        $todayTasks = DailyPlanUtils::getCurrentMissions($queryArgs['user_id']);
        if (empty($todayTasks))
            return genOutput(1000);

        //自取任务的限制
        $extraCount     = 0;  //今日已抽取自取任务数量
        $excludeNotes   = []; //需进行屏蔽的知识点
        foreach ($todayTasks as $task) {
            if ($task->mission_pair == -1) {
                if ($task->action_type == 0) { //自取任务有未完成的
                    return genOutput(1000);
                }
                $extraCount++;
            }

            //已抽取的知识点
            if (in_array($task->mission_type, [DailyPlanUtils::MISSIONTYPE_NOTELEARNING, DailyPlanUtils::MISSIONTYPE_NOTEREVIEW]))
                $excludeNotes[] = $task->mission_content_id;
        }

        //题目数量不够的知识点进行屏蔽
        $excludeNotes[] = 959;
        $excludeNotes[] = 1512;

        //自取任务数量最多为10
        if ($extraCount == 10)
            return genOutput(1000);

        //任务类型元数据
        $missionMeta = DailyPlanUtils::getMissionMeta();

        $userData = DailyPlanUtils::getUserData($queryArgs['user_id']);

        //随机获取一个知识点
        $randomNote = $this->getRandomNote(getExamByExamDetail($userData->testarea_id), unserialize($userData->note_info), $excludeNotes);
        if (empty($randomNote))
            return genOutput(1000);

        //判断任务类型
        $missionType = $randomNote['learned'] ? DailyPlanUtils::MISSIONTYPE_NOTEREVIEW : DailyPlanUtils::MISSIONTYPE_NOTELEARNING;

        //构造表记录
        $args = array(
            'user_id'            => $queryArgs['user_id'],
            'mission_type'       => $missionType,
            'mission_title'      => $randomNote['name'],
            'mission_content_id' => $randomNote['id'],
            'mission_content'    => json_encode([
                'questions'         => $this->genNoteQuestions($randomNote['id']),
                'average_accuracy'  => $randomNote['average_accuracy'],
                'accuracy'          => $randomNote['accuracy'],
                'rate'              => $randomNote['rate']
            ]),
            'action_type'        => 0,
            'mission_pair'       => -1, //表示这是自取任务
            'available'          => 1
        );
        $uddb->insert($uddb->recentMissionInfo, $args);

        //返回数据
        return genOutput(1, [
            'task' => [
                'task_id'    => (int)$uddb->lastInsertId(),
                'type'       => $missionType == DailyPlanUtils::MISSIONTYPE_NOTELEARNING ? '知识点学习' : '知识点复习',
                'content_id' => (int)$randomNote['id'],
                'content'    => '',
                'intro'      => $missionMeta[$missionType]->remark,
                'title'      => $randomNote['name'],
                'subtitle'   => '知识点',
                'done'       => false
            ]
        ]);
    }


    /**
     * 随机获取知识点
     *
     * @param $examId
     * @param $candidates
     * @param $excludes
     * @return int
     */
    private function getRandomNote($examId, &$candidates, &$excludes) {
        global $cmsdb;
        $noteInfo = getNotesByTestId($examId);
        $availableNotes = getNewNoteHierarchy();

        //有归类信息的知识点
        $topicNotes = $cmsdb->getCol('SELECT DISTINCT(`note_id`) FROM `relation_topic_note`');

        foreach ($noteInfo as $row) {
            $notes[$row->note_id] = array(
                'id' => $row->note_id,
                'average_accuracy' => $row->average_accuracy,
                'rate' => $row->rate
            );
        }

        $pool = [];
        foreach ($candidates as $note) {

            //没有统计信息或需要排除
            if (!isset($notes[$note['id']]) || !in_array($note['id'], $topicNotes) || in_array($note['id'], $excludes) || !isset($availableNotes[$note['id']]))
                continue;

            $pool[] = [
                'id'                => $note['id'],
                'name'              => $availableNotes[$note['id']]['name'],
                'average_accuracy'  => $notes[$note['id']]['average_accuracy'],
                'accuracy'          => $note['accuracy'],
                'learned'           => $note['learned'],
                'rate'              => $notes[$note['id']]['rate']
            ];
        }

        if (empty($pool))
            return false;

        //随机抽取
        $randomIndex = rand(0, count($pool));

        return $pool[$randomIndex];
    }

    /**
     * 获取知识点学前学后题目
     *
     * @param $noteId
     * @return array
     */
    private function genNoteQuestions($noteId) {
        global $cmsdb;

        $notes = array(
            'xq' => array(),
            'xh' => array()
        );

        $sql = "SELECT q.id FROM `original_ztk_questions` AS q "
            . "JOIN `relation_question_note` AS r ON (q.id=r.question_id) "
            . "WHERE r.note_id={$noteId} AND q.type=1 AND is_handpick=1";
        $qids = $cmsdb->table()->cache()->raw($sql)->lists('q.id');

        //不足8条则放开限制
        if (count($qids) < 8) {
            $sql = "SELECT q.id FROM `original_ztk_questions` AS q "
                . "JOIN `relation_question_note` AS r ON(q.id=r.question_id) "
                . "WHERE r.note_id={$noteId} AND q.type=1";
            $qids = $cmsdb->table()->cache()->raw($sql)->lists('q.id');
        }

        if (count($qids) >= 8) {
            shuffle($qids);
            $keys = array_rand($qids, 8);
            foreach ($keys as $index => $key) {
                if ($index < 3) {
                    $notes['xq'][] = $qids[$key];
                } else {
                    $notes['xh'][] = $qids[$key];
                }
            }
        }

        return $notes;
    }
}